package com.zbkj.client.utils;

import cn.hutool.json.JSONUtil;
import com.zbkj.common.result.CommonResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 响应工具类
 * +----------------------------------------------------------------------
 * | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 * | Copyright (c) 2016~2025 https://www.crmeb.com All rights reserved.
 * +----------------------------------------------------------------------
 * | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
 * +----------------------------------------------------------------------
 * | Author: CRMEB Team <admin@crmeb.com>
 * +----------------------------------------------------------------------
 */
public class ResponseUtil {

    private static final Logger logger = LoggerFactory.getLogger(ResponseUtil.class);

    /**
     * 返回401未授权错误
     *
     * @param response HttpServletResponse
     * @param message  错误消息
     */
    public static void sendUnauthorizedResponse(HttpServletResponse response, String message) {
        sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, message);
    }

    /**
     * 返回500服务器内部错误
     *
     * @param response HttpServletResponse
     * @param message  错误消息
     */
    public static void sendInternalServerErrorResponse(HttpServletResponse response, String message) {
        sendErrorResponse(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
    }

    /**
     * 返回403禁止访问错误
     *
     * @param response HttpServletResponse
     * @param message  错误消息
     */
    public static void sendForbiddenResponse(HttpServletResponse response, String message) {
        sendErrorResponse(response, HttpServletResponse.SC_FORBIDDEN, message);
    }

    /**
     * 发送错误响应
     *
     * @param response HttpServletResponse
     * @param status   状态码
     * @param message  错误消息
     */
    private static void sendErrorResponse(HttpServletResponse response, int status, String message) {
        try {
            response.setStatus(status);
            response.setContentType("application/json;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            
            CommonResult<String> errorResult = CommonResult.failed(message);
            String jsonResponse = JSONUtil.toJsonStr(errorResult);
            
            PrintWriter writer = response.getWriter();
            writer.write(jsonResponse);
            writer.flush();
            
            logger.debug("发送错误响应: status={}, message={}", status, message);
        } catch (IOException e) {
            logger.error("发送错误响应失败: status={}, message={}", status, message, e);
        }
    }
} 